var qqMap = require('/libs/qqmap-wx-jssdk.min.js');
var qmapSDK;

//app.js
App({
  onLaunch: function() {
    if (wx.getStorageSync('adress')) {
      this.globalData.currentAdress = wx.getStorageSync('adress')
    }
    // 更新版本
    this.updateVersion()
    this.login()
    //获取定位
    this.getLocation()
    //获取选中地址
    this.getAdress()
  },
  globalData: {
    location: [],
    currentAdress: null,
    openId: null,
    host: 'https://demo.urshop.cn/api',
    code: ''
  },
  updateVersion: function() {
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function(res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })
    updateManager.onUpdateReady(function() {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function() {
      // 新版本下载失败
      wx.showModal({
        title: '已经有新版本了~',
        content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
      })
    })
  },
  login: function(e) {
    var that = this
    wx.login({
      success(res) {
        if (res.code) {
          that.globalData.code = res.code;
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      fail(err) {
        wx.showToast({
          title: '登录超时',
          icon: 'none'
        })
      }
    })
  },
  getLocation: function (e) {
    var that = this;
    //初始化
    qmapSDK = new qqMap({
      key: 'Q6JBZ-G3KKJ-RGRFX-FB57R-V3NHJ-O2BKE'
    })
    //获取地址
    wx.getLocation({
      success: function (res) {
        type: 'wgs84'
        qmapSDK.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (e) {
            var adresArr = []
            const addressLocation = e.result.location;
            const courseLat = addressLocation.lat;
            const courseLng = addressLocation.lng;
            var address = {
              latitude: courseLat,
              longitude: courseLng
            }
            adresArr.push(address)
          }
        })
      },
    })
  },
  getAdress: function () {
    var that = this
    wx.request({
      url: that.globalData.host + '/v1/shop/shoplist',
      method: 'get',
      header: {
        "context-type": 'application/json',
      },
      success: function (rep) {
        let adresArr = []
        let oAdres = {}
        let aAdresList = []
        var rep = rep.data
        for (let i = 0; i < rep.Data.length; i++) {
          oAdres = {
            latitude: rep.Data[i].Longitude,
            longitude: rep.Data[i].Latitude
          }
          adresArr.push(oAdres)
          aAdresList.push({
            distance: 0,
            adres: rep.Data[i]
          })
        }
        that.globalData.location = aAdresList
        qmapSDK.calculateDistance({
          to: adresArr,
          success: function (res) {
            for (let i = 0; i < res.result.elements.length; i++) {
              aAdresList[i].distance=res.result.elements[i].distance
            }
           // 距离排序
            function sortNumber(property) {
              return function (a, b) {
                let value1 = a[property];
                let value2 = b[property];
                return value1 - value2;
              }
            }
            aAdresList.sort(sortNumber('distance'))
            if (!(wx.getStorageSync('adress')) && that.globalData.currentAdress == null) {
              that.globalData.currentAdress = aAdresList[0].adres
              wx.setStorageSync('adress',aAdresList[0].adres)
            }
            that.globalData.location = aAdresList
            console.log(that.globalData.location)
          },
          fail: function (err) {

          }
        })
      }
    })
  }
})